package slumpen;

import java.io.PrintStream;
import java.util.ArrayList;

import tools.blast.blastM8Alignment;

public class OrfStat_cluster {

	ArrayList<OrfStat_Orf> store;
	blastM8Alignment ba;
	
	public OrfStat_cluster(){
		store= new ArrayList<OrfStat_Orf>();
		ba= new blastM8Alignment();
	}
	
	public OrfStat_cluster(OrfStat_Orf oo)throws Exception{
		this();
		this.addData(oo);
	}
	
	public void addData(OrfStat_Orf oo)throws Exception{
		if(store.size()==0){
			ba=new blastM8Alignment(oo.ba);
		}else{
			ba.tstart= oo.start<ba.tstart?oo.start:ba.tstart;
			ba.tend=oo.end>ba.tend?oo.end:ba.tend;
			if(!ba.tname.equals(oo.ba.tname)){
				System.err.println("mismatching tnames when adding orf");
			}
		}
		store.add(oo);
	}
	
	public void addData(OrfStat_cluster oc)throws Exception{
		this.store.addAll(oc.store);
		this.ba.tstart=oc.ba.tstart<this.ba.tstart?oc.ba.tstart:this.ba.tstart;
		this.ba.tend=oc.ba.tend>this.ba.tend?oc.ba.tend:this.ba.tend;
		if(!this.ba.tname.equals(oc.ba.tname)){
			System.err.println("mismatching tnames when adding cluster");
		}
	}
	
	public ArrayList<OrfStat_Orf> getLongest()throws Exception{
		ArrayList<OrfStat_Orf> longest= new ArrayList<OrfStat_Orf>();
		boolean[] used=new boolean[store.size()];
//		if(used.length>1)
//			System.out.println(used[0]?"true":"false");
		boolean someLeft=true;
		int max,id;
		while(someLeft){
			//find longest that is left
			max=0;
			id=-1;
			for(int i=0;i<store.size();i++){
				if(!used[i]){
					if(store.get(i).orfLength>max){
						max=store.get(i).orfLength;
						id=i;
					}
				}
			}
			if(id==-1){
				someLeft=false;
			}else{
				longest.add(store.get(id));
				//remove all that overlaps the longest
				for(int i=0;i<store.size();i++){
					if(!used[i]){
						used[i]=store.get(id).overlap(store.get(i));
					}
				}
			}
		}
		
		return longest;
	}
	
	public boolean overlap(OrfStat_Orf oo)throws Exception{
		if(store.size()==0){
			return false;
		}else{
			return ba.overlaps(oo.ba);
		}
	}
	
	public void print(PrintStream out)throws Exception{
		for(OrfStat_Orf oo: getLongest()){
			out.println(oo.toString());
		}
	}
}
